﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using API.Models;
using PPG.DataAccess;
using PPG.CryptoProvider;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Web;

namespace API.Controllers
{
    public class UserChangePasswordController : ApiController
    {
        /// <summary>
        /// Intializing Helper Classes - DB Connection and Security Provider for Encrypting and Decrypting Passwords
        /// Pass in DBServerName, DBUsern
        /// ame and DBPassword from Config File for DB connections
        /// The Security helper does nto take any parameters
        /// </summary>
        DataSourceCommunicator dsComm = new DataSourceCommunicator(DataSourceCommunicator.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"].ToString(), ConfigurationManager.AppSettings["DBUserName"].ToString(), ConfigurationManager.AppSettings["DBPassword"].ToString());
        CryptoAgent securityHandler = new CryptoAgent();

        /// <summary>
        /// Options Resposen for the preflight request of a CORS Opertaions. Will be standard across various functions
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage OptionsValidateUserLogin()
        {
            var response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }

        [ActionName("UserChangePassword")]
        public UserChangePasswordResponse PostUserChangePassword([FromBody]UserChangePasswordRequest request)
        {
            UserChangePasswordResponse response = new UserChangePasswordResponse();
            if (!String.IsNullOrEmpty(request.UserName) && !String.IsNullOrEmpty(request.CurrentPassword))
            {
                string currentpwd;
                dsComm.AddParameter("@ParamUsername", request.UserName);
                string data = dsComm.ExecuteStoredProcedure("dbo.spGetUserPwdByUsername");
                XmlTextReader xReader = new XmlTextReader(data, XmlNodeType.Document, null);
                DataSet UserDataSet = new DataSet();
                UserDataSet.ReadXml(xReader);
                if (UserDataSet.Tables.Count > 0)
                {
                    if (UserDataSet.Tables[0].Rows.Count > 0)
                    {
                        currentpwd = securityHandler.decryptText(UserDataSet.Tables[0].Rows[0][0].ToString());
                        if ((request.CurrentPassword).Equals(currentpwd))
                        {
                            dsComm.AddParameter("@ParamUsername", request.UserName);
                            dsComm.AddParameter("@ParamPassword", securityHandler.EncryptText(request.NewPassword));
                            int datapwd = dsComm.ExecuteNonQuery("dbo.spPostNewPwdByUsername");
                            if (datapwd > 0)
                            {
                                response.StatusMsg = "Password Updated";
                            }
                        }
                        else
                        {
                            response.StatusMsg = "Password doesnt Match";
                        }
                    }
                }
                else
                {
                    response.StatusMsg = "User Not Found";
                }

            }

            return response;
        }
    }
}
